package com.isoft.service.impl;

import com.isoft.entity.DfmeArreEntity;
import com.isoft.mapper.DfmeArreMapper;
import com.isoft.service.DfmeArreService;
import com.isoft.util.XmlParserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Service
public class DfmeArreServiceImpl implements DfmeArreService {
    private static final Logger logger = LoggerFactory.getLogger(DfmeArreServiceImpl.class);

    @Autowired
    private DfmeArreMapper dfmeArreMapper;

    @Autowired
    private XmlParserUtil xmlParserUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(MultipartFile file) throws IOException {
        String xmlContent = new String(file.getBytes(), StandardCharsets.UTF_8);
        logger.info("Processing XML file: {}, size: {} bytes",
                file.getOriginalFilename(), file.getSize());
        return parseAndSave(xmlContent);
    }

    @Override
    public void parseAndSave(DfmeArreEntity entity) {
        processFlightData(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(String xmlContent) {
        try {
            if (xmlContent == null || xmlContent.trim().isEmpty()) {
                throw new IllegalArgumentException("XML内容不能为空");
            }

            DfmeArreEntity entity = xmlParserUtil.parseXml(xmlContent, DfmeArreEntity.class);
            validateEntity(entity);

            processFlightData(entity);

            return "航班到达数据解析成功。航班ID: " + entity.getDflt().getFlightId();
        } catch (Exception e) {
            logger.error("XML处理失败", e);
            throw new RuntimeException("处理XML失败: " + e.getMessage());
        }
    }

    private void validateEntity(DfmeArreEntity entity) {
        if (entity == null || entity.getMeta() == null || entity.getDflt() == null) {
            throw new IllegalArgumentException("XML结构无效，缺少必要节点");
        }

        if (entity.getDflt().getFlightId() == null) {
            throw new IllegalArgumentException("航班ID(FLID)不能为空");
        }

        // 验证状态值
        String status = entity.getDflt().getStatus();
        if (status != null && !status.isEmpty() &&
                !status.matches("NORMAL|DELAYED|CANCELLED|BOARDING|DEPARTED|ALTERNATE|RETURNED|BOARDING_COMPLETED")) {
            logger.warn("无效的航班状态: {}, 将使用默认值NORMAL", status);
            entity.getDflt().setStatus("NORMAL");
        }
    }

    private void processFlightData(DfmeArreEntity entity) {
        try {
            // 1. 先插入元数据
            dfmeArreMapper.insertMeta(entity);
            
            // 2. 插入或更新航班基础信息（使用MERGE语句避免唯一性约束冲突）
            // 参数顺序：flightId, flightAttribute, flightFileId, flightIdentifier, status, status, internalStatus, manualStatus, manualInternalStatus, releaseTime
            // 然后重复相同的参数用于INSERT部分
            dfmeArreMapper.insertFlightBase(entity);
            
            // 3. 插入航班异常信息到FLIGHT_IRREGULARITY表
            dfmeArreMapper.insertIrregularity(entity);
        } catch (DataAccessException e) {
            logger.error("数据库操作失败 - SQL: {}", e.getLocalizedMessage());
            throw new RuntimeException("数据库操作失败: " + e.getMostSpecificCause().getMessage());
        } catch (Exception e) {
            logger.error("处理航班数据时发生意外错误", e);
            throw new RuntimeException("处理航班数据时发生意外错误: " + e.getMessage());
        }
    }
}